package com.eorchis.module.classnotice.ui.controller;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.eorchis.components.attachment.domain.Attachment;
import com.eorchis.components.attachment.service.IAttachmentService;
import com.eorchis.components.attachment.service.UploadConfig;
import com.eorchis.components.attachment.ui.commond.AttachmentCommond;
import com.eorchis.core.service.IBaseService;
import com.eorchis.core.ui.commond.ResultState;
import com.eorchis.core.ui.commond.converter.IQueryCommondAttributeConverter;
import com.eorchis.core.ui.controller.AbstractBaseController;
import com.eorchis.module.classcourse.ui.commond.ClassCourseQueryCommond;
import com.eorchis.module.classnotice.querybean.ClassNoticeQueryBean;
import com.eorchis.module.classnotice.service.IClassNoticeService;
import com.eorchis.module.classnotice.ui.commond.ClassNoticeQueryCommond;
import com.eorchis.module.classnotice.ui.commond.ClassNoticeValidCommond;
import com.eorchis.utils.StringUtils;

/**
 * Title: ClassNoticeController<br>
 * Description: 入学通知管理控制器<br>
 * Company: GoldGov<br>
 * Copyright @ 2012 GoldGov .All rights reserved.<br>
 * @author Max
 * @createDate 2014-12-12
 * @version $Revision$
 */
@Controller("classNoticeController")
@RequestMapping(value = ClassNoticeController.MODULE_PATH)
public class ClassNoticeController 
		extends AbstractBaseController<ClassNoticeValidCommond,ClassNoticeQueryCommond> 
{
	// 模块页面根路径
	public static final String MODULE_PATH = "/module/classnotice";
	// 入学通知接口
	@Autowired
	@Qualifier("com.eorchis.module.classnotice.service.impl.ClassNoticeServiceImpl")
	private IClassNoticeService classNoticeService;
	
	@Autowired
	@Qualifier("attributeConverter")
	private ArrayList<IQueryCommondAttributeConverter> attributeConverter;
	
	@Autowired
	@Qualifier("attachmentService")
	private IAttachmentService attachmentService;
	
	public IBaseService getService() {
		return classNoticeService;
	}

	public String getModulePath() {
		return MODULE_PATH;
	}
	
	/**
	 * 执行添加培训班的逻辑
	 * @param commond
	 * @param bindingResult
	 * @param request
	 * @param response
	 * @param resultState 
	 * @return
	 * @throws Exception
	 * @author Max
	 * @createDate 2014-12-09
	 */
	@RequestMapping(value = "/addNotice")
	public String addNotice(Model modle,@ModelAttribute("result") @Valid ClassNoticeValidCommond vCommond,
			HttpServletRequest request,HttpServletResponse response,@ModelAttribute("resultState") ResultState resultState) throws Exception{
		//if(token.isTokenValid(request, true)){//判断token
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
			for (MultipartFile multipartFile : fileMap.values()) {
				CommonsMultipartFile commonsMultipartFile = (CommonsMultipartFile) multipartFile;
				FileItem item = commonsMultipartFile.getFileItem();
				//File item = new File("D:\\导入1.xls"); 
				//FileInputStream fis = new FileInputStream(item); 
				if (!item.isFormField()) {
					if(item.getSize() == 0) {//附件为空
						resultState.setMessage("The file must be not null");
						resultState.setState(ResultState.RESULT_STATE_FAIL);
						return "";
					}
					if(item.getSize() > getUploadConfig(request).getSizeMax()){//附件大小超出限制
						resultState.setMessage("The file size is too large");
						resultState.setState(ResultState.RESULT_STATE_FAIL);
						return "";
					}
					if(!StringUtils.isContain(FilenameUtils.getExtension(item.getName()), getUploadConfig(request).getFileExtension(),true) && 
							!StringUtils.isContain("*", getUploadConfig(request).getFileExtension())){//配置中不包含的附件扩展名
						resultState.setMessage("Does not allow the extension");
						resultState.setState(ResultState.RESULT_STATE_FAIL);
						return "";
					}
					AttachmentCommond attachmentCommond = makeCommond(null, item);
					try {
						getAttachmentService().save(attachmentCommond);//添加附件记录
						getAttachmentService().getStorage().setAttachmentContent(attachmentCommond,item.getInputStream());//保存附件
						//附件添加成功后和班级进行关联
						String attId=(String) attachmentCommond.getEntityID();
						vCommond.setAttachmentId(attId);
						classNoticeService.save(vCommond);
						
						//resultState.setState(ResultState.RESULT_STATE_SUCCESS);
//						modle.addAttribute(attachmentCommond);
//						modle.addAttribute(resultState);
						resultState.setState(ResultState.RESULT_STATE_SUCCESS);
						resultState.setMessage("添加成功");
					} catch (Exception e) {
						if(attachmentCommond.getAttachmentID() != null) {
							getAttachmentService().delete(new String[] {attachmentCommond.getAttachmentID()});//异常状态删除附件记录
						}
						throw new RuntimeException("get file stream exception.file name:" + FilenameUtils.getName(item.getName()),e);
					}finally{
						//item.delete();
					}
				}
			}
			
		/*}else{
			resultState.setState(ResultState.RESULT_STATE_REPEAT_SUBMIT);//重复提交
			resultState.setMessage("重复提交");
		}*/
		return "forward:"+getModulePath()+"/findList"+getRequestType(request);
	}
	
	
	/**
	 * 获取上传配置对象，首先根据requestURI寻找是否为其配置了独立的上传配置，有则返回，如果没有找到则检测是否配置了全局配置，有则返回，
	 * 如果没有则返回默认的上传配置，即：不限制文件类型，不统计下载数量，且单个文件上传大小限制为5MB
	 * @return 上传配置对象
	 */
	protected UploadConfig getUploadConfig(HttpServletRequest request){
		String requestURI = request.getRequestURI();
		UploadConfig uploadConfig = getAttachmentService().getUploadConfig(requestURI);
		if(uploadConfig == null){
			uploadConfig = getAttachmentService().getUploadConfig();
			//如果上传设置上传配置，则使用默认配置，即：接受所有文件类型，且上传限制为5MB
			if(uploadConfig == null){
				uploadConfig = new UploadConfig();
				uploadConfig.setConfigCode("Default");
				uploadConfig.setFileExtension(new String[]{"*"});
				uploadConfig.setSizeMax(102500*1024*5L);
				uploadConfig.setNeedStatistics(false);
			}
		}
		return uploadConfig;
	}
	
	/**
	 * 根据文件对象封装附件Commond对象
	 * @param groupCode
	 * @param item
	 * @return
	 */
	private AttachmentCommond makeCommond(String groupCode,
			FileItem item) {
		String fileName = FilenameUtils.getName(item.getName());
		AttachmentCommond attachmentCommond = new AttachmentCommond();
		attachmentCommond.setDownloadNumber(0);
		attachmentCommond.setFileName(UUID.randomUUID().toString());
		attachmentCommond.setFileSize(item.getSize());
		attachmentCommond.setPrimevalFileName(fileName);
		attachmentCommond.setFileType(FilenameUtils.getExtension(fileName));
		attachmentCommond.setMimeType(item.getContentType());
		attachmentCommond.setGroupCode(groupCode);
		attachmentCommond.setModifiabilityScope(Attachment.MODIFIABILITY_SCOPE_PUBLIC);
		attachmentCommond.setUploadDate(new Date());
		return attachmentCommond;
	}
	
	private AttachmentCommond makeCommond(String groupCode,
			File item) {
		String fileName = FilenameUtils.getName(item.getName());
		AttachmentCommond attachmentCommond = new AttachmentCommond();
		attachmentCommond.setDownloadNumber(0);
		attachmentCommond.setFileName(UUID.randomUUID().toString());
		//attachmentCommond.setFileSize(item.);
		attachmentCommond.setPrimevalFileName(fileName);
		attachmentCommond.setFileType(FilenameUtils.getExtension(fileName));
		//attachmentCommond.setMimeType(item.getContentType());
		attachmentCommond.setGroupCode(groupCode);
		attachmentCommond.setModifiabilityScope(Attachment.MODIFIABILITY_SCOPE_PUBLIC);
		attachmentCommond.setUploadDate(new Date());
		return attachmentCommond;
	}
	
	protected IAttachmentService getAttachmentService(){
		return attachmentService;
	}
	
	
	/**
	 * 查询班级入学通知
	 * @param qCommond
	 * @param request
	 * @param response
	 * @param resultState
	 * @return
	 * @throws Exception
	 * @author Max
	 * @createDate 2014-12-12
	 */
	@RequestMapping(value = "/findClassNoticeAllList")
	public String findClassNoticeAllList(
			@ModelAttribute("resultList") ClassNoticeQueryCommond qCommond,
			HttpServletRequest request, HttpServletResponse response,
			@ModelAttribute("resultState") ResultState resultState) throws Exception {
		//执行查询逻辑 
		List<ClassNoticeQueryBean> resultList = classNoticeService.findClassNoticeAllList(qCommond);
		//存放结果
		qCommond.setResultList(resultList);
		resultState.setState(ResultState.RESULT_STATE_SUCCESS);
		return getModulePath() + "/list";
	}
	
	/**
	 * 删除入学通知
	 * @param qCommond
	 * @param request
	 * @param response
	 * @param resultState
	 * @return
	 * @throws Exception
	 * @author Max
	 * @createDate 2014-12-12
	 */
	@RequestMapping(value = "/deleteNotic")
	public String deleteNotic(@ModelAttribute("resultList") ClassNoticeQueryCommond qCommond,
			HttpServletRequest request, HttpServletResponse response,
			@ModelAttribute("resultState") ResultState resultState) throws Exception {
		//if(token.isTokenValid(request, true)){//判断token
			classNoticeService.deleteNotic(qCommond);
		/*}else {
			resultState.setState(ResultState.RESULT_STATE_REPEAT_SUBMIT);//重复提交
			resultState.setMessage("重复提交");
		}*/
		return "";
	}
	
	
	/**
	 * 用于排序的方法
	 * @param queryCommond
	 * @param request
	 * @param attributeConverter
	 */
	private void parameterValueConvert(ClassCourseQueryCommond queryCommond,
			HttpServletRequest request,
			List<IQueryCommondAttributeConverter> attributeConverter) {
		for (IQueryCommondAttributeConverter queryCommondAttributeConverter : attributeConverter) {
			queryCommondAttributeConverter.convert(queryCommond,
					request.getParameterMap());
		}
	}
	
	
}
